package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决全局中文乱码的过滤器
 * 解决post提交中文乱码,解决响应的中文的乱码
 */
@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化了");
    }

    public void destroy() {
    }


    //过滤任务
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        //将req,resp强转为子接口HttpServetlRequest/HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //获取前端提交方式
        String method = request.getMethod();
        if("POST".equals(method)){ //POST提交
            //解决POST提交中文乱码
            request.setCharacterEncoding("utf-8") ;
        }

        //处理响应的中文乱码
        response.setContentType("text/html;charset=utf-8") ;

        //放行
        chain.doFilter(request, response);
    }
}
